package cn.itsource.pethome.base.controller;

import cn.itsource.pethome.util.AjaxResult;
import cn.itsource.pethome.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.jsf.FacesContextUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
public class FastFDSController {
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
        //判断文件是否为null
        if(file == null){
            return AjaxResult.error().setMsg("文件不能为空");
        }
        try {
            //获取字节
            byte[] bytes = file.getBytes();
            //获取后缀名
            String filename = file.getOriginalFilename();//获取名字的
            int i = filename.lastIndexOf(".");//获取最后一个点的位置
            String suffix = filename.substring(i+1);//从最后一个点的位置+1把前面所有的字符不要了
            //路径
            String upload = FastdfsUtil.upload(bytes, suffix);
            return AjaxResult.me().setData(upload);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常");
        }
    }
    //  http:127.0.0.1:8080?path=/group1/M00/02/01/CgAIC2NChXOAaB6RAACB2HiLDt4237.jpg
    @DeleteMapping
    public AjaxResult remove(@RequestParam(required = true,value = "path")String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常");
        }
    }
}
